package tech.aistar.day04;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * 本类功能:
 *
 * @author cxylk
 * @date 2020/9/18 12:50
 */
@WebServlet(urlPatterns = "/day04/cookie/*")
public class CookieAction extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo=req.getPathInfo();
        switch (pathInfo){
            case "/add":
                //1.创建一个cookie对象
                //模拟数据 - 就是被封装到cookie对象中的数据
                String uname="日天";
                String pwd="q123";

                //对uname进行一级编码
                uname= URLEncoder.encode(uname,"utf-8");
                //继续对uname进行二级编码
                uname=URLEncoder.encode(uname,"utf-8");

                Cookie c=new Cookie("loginInfo",uname+":"+pwd);
                //还可以设置一些可选的属性
                c.setPath("/");//设置域(代表当前根目录下)

                //设置过期时间 - 单位是s
                c.setMaxAge(60);

                //2.通过响应头将这个cookie发送到客户端
                resp.addCookie(c);

                break;
            case "/get":
                //客服端会通过请求头将本地的cookie发送到server
                //cookie存在多个
                Cookie[] cookies=req.getCookies();
                if(null!=cookies&&cookies.length>0){//清除缓存
                    for (Cookie cookie : cookies) {
                        //String getName();//获取cookie对象的name属性的值
                        if("loginInfo".equals(cookie.getName())){
                            //获取cookie中的value
                            String value=cookie.getValue();
                            String[] arr=value.split(":");

                            //二级编码
                            arr[0]= URLDecoder.decode(arr[0],"utf-8");
                            arr[0]=URLDecoder.decode(arr[0],"utf-8");
//                            System.out.println(arr[0]);
//                            System.out.println(arr[1]);
                        }
                    }
                }
                break;
        }
    }
}
